<template>
  <div class="user-container">
    <div class="top">
      <n-tabs
        type="line"
        size="large"
        :tabs-padding="10"
        pane-style="padding: 10px;"
      >
        <n-tab-pane name="查询数据">
          <n-form
            style="margin-bottom: -24px"
            label-placement="left"
            label-align="right"
            :show-label="true"
            ref="searchFormRef"
            inline
            :label-width="60"
            :model="compData.searchForm"
          >
            <n-grid cols="24" x-gap="10" item-responsive responsive="screen">
              <n-grid-item span="24 m:12 l:8">
                <n-form-item label="用户名" path="name">
                  <n-input
                    v-model:value="compData.searchForm.name"
                    placeholder="输入用户名"
                  />
                </n-form-item>
              </n-grid-item>
              <n-grid-item span="24 m:12 l:8">
                <n-form-item label="邮箱" path="email">
                  <n-input
                    v-model:value="compData.searchForm.email"
                    placeholder="输入邮箱"
                  />
                </n-form-item>
              </n-grid-item>
              <n-grid-item span="24 m:12 l:8">
                <n-form-item>
                  <n-space>
                    <n-button attr-type="button" @click="search">搜索</n-button>
                  </n-space>
                </n-form-item>
              </n-grid-item>
            </n-grid>
          </n-form>
        </n-tab-pane>
        <n-tab-pane name="表格操作">
          <n-space>
            <n-button color="#52C41A" @click="add()"
              >新增数据</n-button
            >
            <n-button color="#ff4d4f" @click="dels()"
              >删除数据</n-button
            >
            <n-button
              color="#1890ff"
              :loading="compData.loading"
              @click="getTableData"
            >
              刷新数据
            </n-button>
            <n-button strong secondary type="success">数据导出</n-button>
            <n-popselect
              v-model:value="compData.tableSizeValue"
              :options="compData.tableSize"
              trigger="click"
            >
              <n-button strong secondary type="warning">表格大小</n-button>
            </n-popselect>
            <n-popover trigger="click" placement="bottom">
              <template #trigger>
                <n-button strong secondary type="info">设置表列</n-button>
              </template>
              <n-checkbox-group
                v-model:value="compData.columnsOptionsValue"
                @update:value="handleColumnsOptions"
              >
                <n-space vertical align="start">
                  <n-checkbox
                    v-for="item in compData.columnsOptions"
                    :value="item.key"
                    :label="item.title"
                    :disabled="item.disabled"
                  ></n-checkbox>
                </n-space>
              </n-checkbox-group>
            </n-popover>
          </n-space>
        </n-tab-pane>
      </n-tabs>
    </div>
    <div class="bottom">
      <n-data-table
        :bordered="false"
        :bottom-bordered="false"
        :columns="compData.columns"
        :data="compData.tableData"
        :pagination="compData.pagination"
        :single-line="false"
        :loading="compData.loading"
        :size="compData.tableSizeValue"
        :row-key="compData.rowKey"
        :flex-height="true"
        @update:checked-row-keys="check"
      />
      <n-pagination
        v-model:page="compData.pageNumber"
        v-model:page-size="compData.pageSize"
        :page-count="compData.pageCount"
        :page-sizes="[10, 20, 30, 40]"
        size="large"
        show-quick-jumper
        show-size-picker
        style="justify-content: flex-end; flex: 1"
        @update:page="updatePage"
        @update:page-size="updatePageSize"
      />
    </div>
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref } from "vue";
import { useMessage } from "naive-ui";
import type { FormInst } from "naive-ui";
import { searchUser, delUser } from "@/app/admin/api/user.ts";
import { createColumns, tableSize } from "@/app/admin/view/user/data";
import { useRouter } from "vue-router";
import { onMounted } from "vue";
import { getRoleList } from "../../api/role";

const router = useRouter();
const searchFormRef = ref<FormInst | null>(null);
const message = useMessage();
const compData: any = reactive({
  tableData: [],
  tableSizeValue: "medium",
  tableSize,
  loading: true,
  defaultExpandedKeys: ["1", "2"],
  columns: [],
  columnsOptions: [],
  columnsOptionsValue: [],
  searchForm: { name: "", email: "" },
  pagination: false,
  pageCount: 1, // 页数
  pageSize: 10, // 每页条数
  pageNumber: 1, // 当前第几页
  rowKey: (row: any) => row.uid,
  checkedRowKeys: [],
});

// 当前页发生变化
const updatePage = (page: number) => {
  compData.pageNumber = page;
  getTableData();
};

// 分页大小发生变化
const updatePageSize = (pageSize: number) => {
  compData.pageSize = pageSize;
  getTableData();
};

// 搜索
const search = () => {
  getTableData();
};

// 获取表格数据
const getTableData = (params = {}) => {
  compData.checkedRowKeys = [];
  const _params = {
    ...params,
    pageSize: compData.pageSize,
    pageNumber: compData.pageNumber,
    name: compData.searchForm.name,
    email: compData.searchForm.email, // 暂不支持
  };
  compData.loading = true;
  searchUser(_params)
    .then((res: any) => {
      compData.tableData = (res.data?.list || []).map((item: any) => {
        if (!item.rid) return item;
        const _rid = item.rid.split(",");
        const ridNames = _rid.map((i: any) => {
          return (ridOptions.value?.find((j: any) => i === j.value) || {})?.label || "";
        });
        return {
          ...item,
          ridNames: ridNames.join(","),
        }
      });
      
      compData.pageCount = Math.ceil(res.data.total / res.data.pageSize);
    })
    .catch((err: any) => {
      window.$message.success(err || "获取用户失败");
    })
    .finally(() => {
      compData.loading = false;
    });
}

const del = (uid: Array<number | string>) => {
  delUser({ uid })
    .then((res: any) => {
      if (res.status === "success") {
        window.$message.success(`删除成功，${uid}`);
        getTableData();
      } else {
        window.$message.error("删除失败");
      }
    })
    .finally(() => {
      compData.loading = false;
    });
}
// 删除用户
const dels = () => {
  if (compData.checkedRowKeys.length) {
    del(compData.checkedRowKeys);
  } else {
    message.warning("请选择要删除的项");
  }
}

// 新增
const add = () => {
  router.push("/user/add");
}


// 编辑
const edit = (uid: number | string) => {
  router.push("/user/edit/" + uid);
}

// 选择列表复选框
const check = (rowKeys: any) => {
  compData.checkedRowKeys = rowKeys;
}

let sourceColumns: any[] = [];
// 设置表列
sourceColumns = createColumns({ edit, del });
compData.columns = sourceColumns;
compData.columnsOptionsValue = sourceColumns.map(
  (item: any) => item.key
);
compData.columnsOptions = sourceColumns
  .filter((item: any) => item.type !== "selection")
  .map((item: any) => {
    if (item.key === "actions") {
      item.disabled = true;
    }
    return item;
  });

// 操作 - 设置列
const handleColumnsOptions = (value: (string | number)[]) => {
  compData.columns = sourceColumns.filter(
    (item: any) => value.indexOf(item.key) !== -1
  );
};

// 获取角色选项
const ridOptions = ref([]);
const getRidOptions = async () => {
  const res = await getRoleList({
    pageNumber: 1,
    pageSize: 100,
  });
  ridOptions.value = (res?.data?.list || []).map(i => ({
    label: i.name,
    value: i.rid,
  }));
};

onMounted(async () => {
  await getRidOptions();
  getTableData();
});
</script>

<style lang="less" scoped>
.user-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  .top {
    margin-bottom: 8px;
  }
  .bottom {
    flex: auto;
    overflow: hidden;
    .n-data-table {
      height: calc(100% - 34px);
    }
    .n-pagination {
      height: 34px;
    }
  }
}
</style>
